<?php
/**
 * 修改历史
 * 修改时间：2018/2/01
 * 修改人：lizenan
 * 修改功能：【商城需求】商品图片上增加促销打标
 * 任务ID：495
 */
namespace backend\controllers;

use yii\web\AdminController;
use backend\models\UploadForm;
use Yii;
use backend\models\ActivityMessage;
use backend\models\ActivityMessagePlus;
use backend\models\GoodsSaleEdit;
use PHPExcel;
use common\helps\tools;

class ActivityMessageController extends AdminController
{
    public $layout = false;
    //业务关键字
    public $service = 'ActivityMessage';
    //活动列表页
    public function actionIndex(){
        $model = new UploadForm();
        return $this->render('index',['model'=>$model]);
    }
    
    public function actionGetActivityMessage(){
        $data = Yii::$app->request->post();
        $title = $data['activity_message_title'];
        $query = ActivityMessage::find()->select('id,title,activity_start_date,activity_end_date,use_flg');
        if ($title){
            $query = $query->where(['like','title',$title]);
        }
        $count = $query->count();
        $list = $query->offset($data['start'])->limit($data['length'])->orderBy('id desc')->asArray()->all();
        $result['draw'] = intval($data['draw']);
        $result['recordsTotal'] = intval($count);
        $result['recordsFiltered'] = intval($count);
        $result['data'] = $list;
        return \yii\helpers\Json::encode($result);
    }
    
    public function actionActivityMessageDetail(){
        $data = Yii::$app->request->post();
        $result = ActivityMessage::find()->where('id=:id',[':id'=>$data['id']])->asArray()->one();
        $detail = ActivityMessagePlus::find()->select('id,type,category_id,sku,goods_name_cn,sort')
            ->where('activity_message_id=:activity_message_id',[':activity_message_id'=>$data['id']])->orderBy('sort asc')->asArray()->all();
        $result['plus'] = $detail;
        $this->retJson($result,200);
    }
    
    public function actionChangeActivityMessage(){
        $model = new ActivityMessage();
        $data = Yii::$app->request->post();
        $transaction = Yii::$app->db->beginTransaction();
        try {
            $id = $data['activity_message_id'];
            $oper = $model->getCreator();
            $oper_time = date('Y-m-d H:i:s');
            if (!tools::arrayHasValue($data,'activity_title')){
                throw new \Exception('请填写活动标题');
            }
            $title = $data['activity_title'];
            if (mb_strlen($title) > 25){
                throw new \Exception('活动标题字数最多25个字（包含标点符号）');
            }
            if (!tools::arrayHasValue($data,'reservationtime')){
                throw new \Exception('请选择活动时间');
            }
            $reservationtime = $data['reservationtime'];
            $time_a = explode(' - ', $reservationtime);
            $activity_start_date = $time_a[0];
            $activity_end_date = $time_a[1];
            if (!$activity_start_date || !$activity_end_date){
                throw new \Exception('时间格式错误，请重新选择活动日期时间段');
            }
            $activity_identification = $data['activity_identification'];
            //add by lizenan 20180201 【商城需求】商品图片上增加促销打标 495 start
            $activity_identification_style = intval($data['activity_identification_style']);
            if ($activity_identification && $activity_identification_style == 0){
                throw new \Exception('请选择活动标识展示样式');
            }
            //add by lizenan 20180201 【商城需求】商品图片上增加促销打标 495 end
            $activity_url = $data['activity_url'];
            $use_flg = $data['use_flg'];
            $plus_1 = tools::arrayHasValue($data,'activity_message_plus_1') ? $data['activity_message_plus_1'] : [];
            $plus_2 = tools::arrayHasValue($data,'activity_message_plus_2') ? $data['activity_message_plus_2'] : [];
            $sku = tools::arrayHasValue($data,'sku') ? $data['sku'] : [];
            $category = tools::arrayHasValue($data,'category') ? $data['category'] : [];
            if (is_array($category) && count($category) > 0) {
                if (count($category) != count(array_unique($category))) {
                    throw new \Exception('分类名称选项不可重复，请检查后重新选择');
                }
            }
            if (is_array($sku) && count($sku) > 0) {
                if (count($sku) != count(array_unique($sku))){
                    throw new \Exception('物料号不可重复，请检查后重新填写');
                }
            }
            if (count($sku) == 0 && count($category) == 0){
                throw new \Exception('请选择至少填写一个活动分类或商品');
            }
            if (count($sku) > 0){
                $sale_sku = GoodsSaleEdit::find()->select('sku,goods_name_cn')->where(['in','sku',$sku])->asArray()->all();
                if (count($sale_sku) != count($sku)) {
                    throw new \Exception('有填写的物料号不存在');
                }
                $sale_sku = array_combine(array_column($sale_sku, 'sku'),$sale_sku);
            }
            $plus_ids_1 = $plus_ids_2 = [];
            if ($id){
                $model = ActivityMessage::findOne($id);
                $where_plus = ['activity_message_id'=>$id];
                $plus_category = ActivityMessagePlus::find()->where($where_plus+['type'=>1])->asArray()->all();
                $plus_sku = ActivityMessagePlus::find()->where($where_plus+['type'=>2])->asArray()->all();
                $plus_ids_1 = array_column($plus_category, 'id');
                $plus_ids_2 = array_column($plus_sku, 'id');
                $model->editor = $oper;
                $model->edit_time = $oper_time;
            }else{
                $model->creator = $oper;
                $model->create_time = $oper_time;
            }
            $model->title = $title;
            $model->activity_start_date = $activity_start_date;
            $model->activity_end_date = $activity_end_date;
            $model->use_flg = $use_flg;
            $model->activity_identification = $activity_identification;
            //add by lizenan 20180201 【商城需求】商品图片上增加促销打标 495 start
            $model->activity_identification_style = $activity_identification_style;
            //add by lizenan 20180201 【商城需求】商品图片上增加促销打标 495 end
            $model->activity_url = $activity_url;
            $model->save();
            $id = $model->attributes['id'];
            if (!$id){
                throw new \Exception('操作失败，请重试');
            }
            $sort = $sort1 = 1;
            if (is_array($plus_1) && count($plus_1) > 0)for ($i=0;$i<count($plus_1);$i++){
                if (!$category[$i] && $category[$i] !== '0') continue;
                $plus = new ActivityMessagePlus();
                if ($plus_1[$i]){
                    $plus = $plus->findOne($plus_1[$i]);
                    $plus->editor = $oper;
                    $plus->edit_time = $oper_time;
                }else{
                    $plus->creator = $oper;
                    $plus->create_time = $oper_time;
                    $plus->type = 1;
                }
                $plus->activity_message_id = $id;
                $plus->category_id = $category[$i];
                $plus->sort = $sort;
                $plus->save();
                $plus_id = $plus->attributes['id'];
                if (!$plus_id){
                    throw new \Exception('商品分类添加失败');
                }
                $sort++;
            }
            if (is_array($plus_2) && count($plus_2) > 0){
                for ($j=0;$j<count($plus_2);$j++){
                    if (!$sku[$j]) continue;
                    $plus = new ActivityMessagePlus();
                    if ($plus_2[$j]){
                        $plus = $plus->findOne($plus_2[$j]);
                        $plus->editor = $oper;
                        $plus->edit_time = $oper_time;
                    }else{
                        $plus->creator = $oper;
                        $plus->create_time = $oper_time;
                        $plus->type = 2;
                    }
                    $plus->activity_message_id = $id;
                    $plus->sku = $sku[$j];
                    $plus->goods_name_cn = $sale_sku[$sku[$j]]['goods_name_cn'];
                    $plus->sort = $sort1;
                    $plus->save();
                    $plus_id = $plus->attributes['id'];
                    if (!$plus_id){
                        throw new \Exception('商品分类添加失败');
                    }
                    $sort1++;
                }
            }
            if (is_array($plus_ids_1) && count($plus_ids_1))foreach ($plus_ids_1 as $ids_1){
                if (!in_array($ids_1,$plus_1)){
                    $del = ActivityMessagePlus::deleteAll(['id'=>$ids_1]);
                    if(!$del){
                        throw new \Exception('操作失败');
                    }
                }
            }
            if (is_array($plus_ids_2) && count($plus_ids_2))foreach ($plus_ids_2 as $ids_2){
                if (!in_array($ids_2,$plus_2)){
                    $del = ActivityMessagePlus::deleteAll(['id'=>$ids_2]);
                    if(!$del){
                        throw new \Exception('操作失败');
                    }
                }
            }
            $transaction->commit();
            $this->retJson('编辑成功',200);
        } catch (\Exception $e) {
            $transaction->rollBack();
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionChangeActivityMessageStatus(){
        $data_now = array();
        $model = new ActivityMessage();
        $data = Yii::$app->request->post();
        $data_now['use_flg'] = $data['use_flg'];
        $data_now['editor'] = $model->getCreator();
        $data_now['edit_time'] = date('Y-m-d H:i:s',time());
        $where = ['id'=>$data['id']];
        $ret = $model::updateAll($data_now,$where);
        if(!$ret){
            $this->retJson('操作失败',500);
        }
        $this->retJson('操作成功',200);
    }
    
    public function actionExcelFileUpload(){
        try {
            if (count ( $_FILES ) == 0) {
                throw new \Exception('未上传文件');
            }
            $fileElementName = array_keys ( $_FILES );
            $fileElementName = $fileElementName [0];
            
            if (! $_FILES [$fileElementName]){
                throw new \Exception('未上传文件');
            }
            $file = $_FILES [$fileElementName];
            if($_FILES[$fileElementName]['size'] > 2097152) {//文件不能超过2M
                throw new \Exception('文件大小超过2M');
            }
            // 验证文件类型
            $lastdot = strrpos ( $file ['name'], "." ); // 找到区分文件名与扩展名的标记符“.”最后出现的位置
            $reader_type = substr ( $file ['name'], $lastdot + 1 ); // 取出扩展名
            $allowType = array ('xls','xlsx');
            if (! in_array ( strtolower ( $reader_type ), $allowType )) {
                throw new \Exception('只支持xls,xlsx文件');
            }
            $extend = ($reader_type == 'xlsx' ? 'Excel2007' : 'Excel5');
            set_time_limit(0);
            $excel = new PHPExcel();
            $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_serialized;
            $cacheSettings = array();
            \PHPExcel_Settings::setCacheStorageMethod($cacheMethod,$cacheSettings);
            $objReader = \PHPExcel_IOFactory::createReader($extend);
            $objPHPExcel = $objReader->load($file ['tmp_name']);
            $objWorksheet = $objPHPExcel->getActiveSheet();
            $highestRow = $objWorksheet->getHighestRow();
            if($highestRow < 2){
                throw new \Exception('上传文件数据不能为空');
            }
            if($highestRow > 1001){
                throw new \Exception('上传文件数据超过行数限制,最大不能超过一千条');
            }
            
            $highestColumn = $objWorksheet->getHighestColumn();// 取得总列数
            $highestColumnIndex = \PHPExcel_Cell::columnIndexFromString ( $highestColumn ); // 总列数
            $dataKey = array();
            //商品导入标题对应键
            $excelTitle = array('sku'=>'SKU（物料号）');
            $dataKey = array_keys($excelTitle);
            $title = array_values($excelTitle);
            //获取数据集合
            $excelDataBefore = $excelData = $fileTitle = $data_arr =  array();
            for ($r = 1; $r <= $highestRow ;$r++){
                for($c = 0; $c < $highestColumnIndex; $c ++) {
                    $getCellByColumnAndRowResult = trim ( $objWorksheet->getCellByColumnAndRow ( $c, $r )->getValue () );
                    if($r == 1){
                        $fileTitle [] = $getCellByColumnAndRowResult;
                    }else if(array_key_exists($c, $dataKey)){
                        $excelDataBefore[][$dataKey[$c]] = $excelData[][$dataKey[$c]] =  $getCellByColumnAndRowResult;
                    }
                }
            }
            if(count($excelData) == 0) throw new \Exception('未解析到可用数据');
            $fieldsTitle=array();
            $i = 2;
            foreach ($title as $k =>$v){
                if($v !== $fileTitle[$k]){
                    throw new \Exception('上传文件标题('.$fileTitle[$k].')格式不正确,应为'.$v);
                }
            }
            return $this->retJson($excelData,200);
        } catch (\Exception $e) {
            //add by allen.qiang 20180112 异常处理，日志优化 start
            error_log('error->' . __METHOD__ . ' error:' . $e->getMessage());
            //add by allen.qiang 20180112 异常处理，日志优化 end
            return $this->retJson($e->getMessage(),500);
        }
    }
    
    public function actionValidateSku(){
        $data = Yii::$app->request->post();
        $sku = $data['sku'];
        if (!$sku) return false;
        $goods_sale = GoodsSaleEdit::find()->select('goods_name_cn')->where('sku=:sku',[':sku'=>$sku])->asArray()->one();
        if ($goods_sale['goods_name_cn']) {
            $this->retJson($goods_sale['goods_name_cn'],200);
        }else{
            $this->retJson('物料号'.$sku.'，请确认物料号是否正确',500);
        }
    }
}